//
//  Problem125.swift
//  TestProject
//
//  Created by 毕武侠 on 2021/3/28.
//  Copyright © 2021 zhulong. All rights reserved.
//

import UIKit

/*
 125. 验证回文串
 给定一个字符串，验证它是否是回文串，只考虑字母和数字字符，可以忽略字母的大小写。
 说明：本题中，我们将空字符串定义为有效的回文串。

 示例 1:
     输入: "A man, a plan, a canal: Panama"
     输出: true
 示例 2:
     输入: "race a car"
     输出: false
 */
@objcMembers class Problem125: NSObject {
    func solution() {
        print(isPalindrome("A man, a plan, a canal: Panama"))
        print(isPalindrome("race a car"))
    }
    
    /*
     从左右2端对比字符串，跳过遇到非字母和数字的字符
     */
    func isPalindrome(_ s: String) -> Bool {
        if s.count <= 1 {
            return true
        }
        var start = 0
        var end = s.count - 1
        let charts = Array(s)
        var startAscii: UInt8 = 0
        var endAscii: UInt8 = 0
        
        while start < end {
            startAscii = charts[start].asciiValue!
            if (startAscii >= 97 && startAscii <= 122) || (startAscii >= 65 && startAscii <= 90) || (startAscii >= 48 && startAscii <= 57)  {
                startAscii = startAscii >= 97 ? startAscii - 32 : startAscii
            } else {
                start += 1
                continue
            }
            
            endAscii = charts[end].asciiValue!
            if (endAscii >= 97 && endAscii <= 122) || (endAscii >= 65 && endAscii <= 90) || (endAscii >= 48 && endAscii <= 57)  {
                endAscii = endAscii >= 97 ? endAscii - 32 : endAscii
            } else {
                end -= 1
                continue
            }
            
            if startAscii != endAscii {
                return false
            }
            
            start += 1
            end -= 1
        }
        
        return true
    }
}
